package com.javaspeak.designpatterns.go4.creational.prototype;

import java.util.EnumMap;
import java.util.Map;

import com.javaspeak.designpatterns.go4.creational.singleton.Square;

/**
 * This class is the main part of the prototype pattern.
 * <p>
 * There is a map of instances.  When a certain instance is requested using
 * the getShape() method the relevant Shape instance is retrieved and then
 * cloned.
 *
 * @author John Dickerson
 */
public class ProtypeFactory {

    private static Map<ShapeType,Shape> shapeCache =
        new EnumMap<ShapeType,Shape>( ShapeType.class );

    static {
        shapeCache.put( ShapeType.SQUARE  , new Square() );
        shapeCache.put( ShapeType.TRIANGLE  , new Triangle() );
    }


    /**
     * Retrieves a Shape from the map and clones it
     *
     * @param shapeType the kind of Shape to retrieve
     * @return the Shape
     * @throws CloneNotSupportedException Thrown if the the Shape does not
     * implement Cloneable
     */
    public static Shape getShape( ShapeType shapeType )
        throws CloneNotSupportedException{

        return ( Shape )shapeCache.get( shapeType ).clone();
    }
}
